﻿using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

namespace Plorx
{
    class GoogleGeocode
    {
        private const int tries = 10;
        private const int timeout = 1000;
        public static Dictionary<string, object> Location(string _address)
        {
            if ((_address == null) || (_address.Length == 0))
            {
                return null;
            }
            try
            {
                object _o;
                int _tries = tries;
                string _error;
                do
                {
                    if (_tries != tries)
                    {
                        Thread.Sleep(timeout);
                    }
                    _o = (new JavaScriptSerializer()).DeserializeObject(new StreamReader(WebRequest.Create("http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" + _address).GetResponse().GetResponseStream()).ReadToEnd());
                    _error = (_o as Dictionary<string, object>)["status"] as string;
                }
                while ((_tries-- > 0) && (_error == "OVER_QUERY_LIMIT"));
                if (_error != "OK")
                {
                    return null;
                }
                Dictionary<string, object> _result = ((((_o as Dictionary<string, object>)["results"] as object[])[0] as Dictionary<string, object>)["geometry"] as Dictionary<string, object>)["location"] as Dictionary<string, object>;
                _result["formatted_address"] = (((_o as Dictionary<string, object>)["results"] as object[])[0] as Dictionary<string, object>)["formatted_address"] as string;
                return _result;
            }
            catch (ThreadInterruptedException e)
            {
                throw e;
            }
            catch
            {
            }
            return null;
        }
        public static Dictionary<string, object>[] Locations(string[] _addresses)
        {
            if (_addresses == null)
            {
                return null;
            }
            var _locations = new Dictionary<string, object>[_addresses.Length];
            for (int _i = 0; _i < _addresses.Length; _i++)
            {
                _locations[_i] = Location(_addresses[_i]);
            }
            return (_locations);
        }
        public static string ObjectToJSON(object _o)
        {
            var _sb = new StringBuilder(null);
            (new JavaScriptSerializer()).Serialize(_o, _sb);
            return _sb.ToString();
        }
    }
}
